import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ladder_cash/app/com/service/reported_data_service.dart';
import 'package:liuxlcommon/view/loading_view.dart';
import 'package:ladder_cash/app/com/manage/location_manage/location_manage.dart';
import 'package:ladder_cash/app/page/home/home_listener.dart';
import 'package:ladder_cash/app/page/home/home_logic.dart';
import 'package:ladder_cash/app/page/index/large_card_page.dart';
import 'package:ladder_cash/app/page/index/small_card_page.dart';
import 'package:ladder_cash/value/app_colors.dart';

import 'index_logic.dart';
import 'large_card/LargeCard.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>
    with
        AutomaticKeepAliveClientMixin,
        HomeListener,
        SingleTickerProviderStateMixin {
  final logic = Get.put(IndexLogic());
  final GlobalKey<RefreshIndicatorState> _indicatorKey =
      GlobalKey<RefreshIndicatorState>();

  @override
  void initState() {
    super.initState();
    Get.find<HomeLogic>().mapHomeListener["index"] = this;
    ReportedDataService().reportData(goToSetting: false);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<IndexLogic>(
        builder: (logic) => RefreshIndicator(
            key: _indicatorKey,
            color: AppColors.primaryColor,
            child: LoadingView(
              isPullDown: true,
              future: () => logic.getIndexData(),
              datas: logic.indexData,
              onSuccess: () {
                if (logic.indexData != null) logic.update();
              },
              onStateClick: (LoadState state) {
                if (state == LoadState.ERROR || state == LoadState.EMPTY) {
                  logic.update();
                }
              },
              // body: () =>  SmallCardPage(),
              body: () => logic.isLargeCard ? LargeCard() : SmallCardPage(),
            ),
            onRefresh: () async => await logic.getIndexData(refresh: true)));
  }

  @override
  void dispose() {
    // Get.delete<IndexLogic>();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void onHomePageChanged(position) {
    if (position != 0) return;
    //已经加载完成了， 下次进入做刷新
    if (logic.indexData != null) {
      _indicatorKey.currentState?.show();
    }
    LocationManage.instance.determinePosition().then((value) {
      print(json.encode(value.toString()));
    });

    ReportedDataService().locationPermission(goToSetting: false).then((ok) {
      if (ok) ReportedDataService().reportData(goToSetting: false);
    });
  }
}
